<template>
  <a-layout style="min-height: 100vh; background: #f5f7fa;">
    <nav-bar />

    <a-layout-content style="padding: 30px 50px; max-width: 1400px; margin: 0 auto; width: 100%;">
      <div style="max-width: 1400px; margin: 0 auto;">
        <a-card title="导入历史记录" style="border-radius: 8px; border: 1px solid #e4e7ed;">
          <template #extra>
            <a-button @click="fetchHistory" :loading="loading">
              <template #icon><reload-outlined /></template>
              刷新
            </a-button>
          </template>

          <a-table
            :dataSource="history"
            :columns="columns"
            :loading="loading"
            :pagination="pagination"
            row-key="id"
            bordered
          >
            <template #bodyCell="{ column, record }">
              <template v-if="column.key === 'status'">
                <a-tag :color="record.status === 'success' ? 'green' : 'red'">
                  {{ record.status === 'success' ? '成功' : '失败' }}
                </a-tag>
              </template>

              <template v-else-if="column.key === 'import_time'">
                {{ formatTime(record.import_time) }}
              </template>

              <template v-else-if="column.key === 'action'">
                <a-space>
                  <a-button
                    type="primary"
                    size="small"
                    @click="showRollbackModal(record)"
                    :disabled="rollbackLoading"
                  >
                    <template #icon><history-outlined /></template>
                    回滚
                  </a-button>
                  
                  <a-tooltip title="查看详细信息">
                    <a-button size="small" @click="showDetailModal(record)">
                      <template #icon><file-outlined /></template>
                      详情
                    </a-button>
                  </a-tooltip>
                </a-space>
              </template>
            </template>
          </a-table>
        </a-card>
      </div>
    </a-layout-content>

    <a-layout-footer style="text-align: center; background: #ffffff; color: #606266; border-top: 1px solid #e4e7ed;">
      <div style="padding: 16px 0;">
        <p style="margin: 0;">蛋白质数据库管理系统 ©2025</p>
      </div>
    </a-layout-footer>
  </a-layout>

  <!-- 回滚确认对话框 -->
  <a-modal
    v-model:open="rollbackModalVisible"
    title="确认回滚"
    @ok="handleRollback"
    :confirm-loading="rollbackLoading"
    ok-text="确认回滚"
    cancel-text="取消"
  >
    <a-alert
      message="警告"
      description="回滚操作将恢复数据库到选定版本的状态，此操作不可撤销。回滚后，该版本之后的所有数据将被删除。请确认是否继续？"
      type="warning"
      show-icon
      style="margin-bottom: 16px;"
    />
    
    <div v-if="selectedRecord">
      <a-descriptions :column="1" bordered size="small">
        <a-descriptions-item label="历史版本 ID">
          {{ selectedRecord.id }}
        </a-descriptions-item>
        <a-descriptions-item label="文件名">
          {{ selectedRecord.file_name }}
        </a-descriptions-item>
        <a-descriptions-item label="导入时间">
          {{ formatTime(selectedRecord.import_time) }}
        </a-descriptions-item>
        <a-descriptions-item label="导入行数">
          {{ selectedRecord.row_count }}
        </a-descriptions-item>
      </a-descriptions>
    </div>
  </a-modal>

  <!-- 详情对话框 -->
  <a-modal
    v-model:open="detailModalVisible"
    title="导入详情"
    :footer="null"
    width="600px"
  >
    <div v-if="selectedDetailRecord">
      <a-descriptions :column="1" bordered size="small">
        <a-descriptions-item label="历史版本 ID">
          {{ selectedDetailRecord.id }}
        </a-descriptions-item>
        <a-descriptions-item label="文件名">
          <a-typography-text copyable>{{ selectedDetailRecord.file_name }}</a-typography-text>
        </a-descriptions-item>
        <a-descriptions-item label="导入时间">
          {{ formatTime(selectedDetailRecord.import_time) }}
        </a-descriptions-item>
        <a-descriptions-item label="导入行数">
          {{ selectedDetailRecord.row_count?.toLocaleString() || 0 }} 行
        </a-descriptions-item>
        <a-descriptions-item label="状态">
          <a-tag :color="selectedDetailRecord.status === 'success' ? 'green' : 'red'">
            {{ selectedDetailRecord.status === 'success' ? '成功' : '失败' }}
          </a-tag>
        </a-descriptions-item>
        <a-descriptions-item label="备份文件路径">
          <div style="display: flex; align-items: center; gap: 8px;">
            <a-typography-text 
              :copyable="{ text: selectedDetailRecord.backup_file || '无' }"
              :style="{ 
                flex: 1, 
                wordBreak: 'break-all',
                fontFamily: 'monospace',
                fontSize: '12px'
              }"
            >
              {{ selectedDetailRecord.backup_file || '无备份文件' }}
            </a-typography-text>
            <a-button 
              v-if="selectedDetailRecord.backup_file"
              type="link" 
              size="small"
              @click="copyBackupPath(selectedDetailRecord.backup_file)"
            >
              <template #icon><copy-outlined /></template>
              复制路径
            </a-button>
          </div>
        </a-descriptions-item>
      </a-descriptions>
      
      <a-divider />
      
      <div style="margin-top: 16px;">
        <a-space>
          <a-button 
            type="primary"
            @click="showRollbackModal(selectedDetailRecord)"
            :disabled="selectedDetailRecord.status !== 'success'"
          >
            <template #icon><history-outlined /></template>
            回滚到此版本
          </a-button>
          <a-button @click="detailModalVisible = false">
            关闭
          </a-button>
        </a-space>
      </div>
    </div>
  </a-modal>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { 
  ReloadOutlined, 
  HistoryOutlined, 
  FileOutlined,
  CopyOutlined
} from '@ant-design/icons-vue'
import { message, Modal } from 'ant-design-vue'
import axiosInstance from '../utils/axios'
import NavBar from '../components/NavBar.vue'
const loading = ref(false)
const rollbackLoading = ref(false)
const history = ref([])
const rollbackModalVisible = ref(false)
const selectedRecord = ref(null)
const detailModalVisible = ref(false)
const selectedDetailRecord = ref(null)

const columns = [
  {
    title: 'ID',
    dataIndex: 'id',
    key: 'id',
    width: 80,
    align: 'center'
  },
  {
    title: '文件名',
    dataIndex: 'file_name',
    key: 'file_name',
    ellipsis: true
  },
  {
    title: '导入时间',
    dataIndex: 'import_time',
    key: 'import_time',
    width: 180
  },
  {
    title: '导入行数',
    dataIndex: 'row_count',
    key: 'row_count',
    width: 120,
    align: 'center'
  },
  {
    title: '状态',
    dataIndex: 'status',
    key: 'status',
    width: 100,
    align: 'center'
  },
  {
    title: '操作',
    key: 'action',
    width: 180,
    align: 'center'
  }
]

const pagination = {
  pageSize: 10,
  showSizeChanger: true,
  showQuickJumper: true,
  showTotal: (total) => `共 ${total} 条记录`
}

const fetchHistory = async () => {
  loading.value = true
  try {
    const response = await axiosInstance.get('/history/')
    history.value = response.data
  } catch (error) {
    console.error('获取历史记录失败:', error)
    message.error('获取历史记录失败：' + (error.response?.data?.detail || error.message))
  } finally {
    loading.value = false
  }
}

const showRollbackModal = (record) => {
  selectedRecord.value = record
  rollbackModalVisible.value = true
  detailModalVisible.value = false // 关闭详情模态框
}

const showDetailModal = (record) => {
  selectedDetailRecord.value = record
  detailModalVisible.value = true
}

const copyBackupPath = (path) => {
  if (navigator.clipboard) {
    navigator.clipboard.writeText(path).then(() => {
      message.success('备份文件路径已复制到剪贴板')
    }).catch(() => {
      message.error('复制失败，请手动复制')
    })
  } else {
    // 降级方案
    const textArea = document.createElement('textarea')
    textArea.value = path
    document.body.appendChild(textArea)
    textArea.select()
    try {
      document.execCommand('copy')
      message.success('备份文件路径已复制到剪贴板')
    } catch (err) {
      message.error('复制失败，请手动复制')
    }
    document.body.removeChild(textArea)
  }
}

const handleRollback = async () => {
  if (!selectedRecord.value) return

  rollbackLoading.value = true
  try {
    const response = await axiosInstance.post(
      `/rollback/${selectedRecord.value.id}`
    )
    
    message.success('数据库回滚成功！')
    rollbackModalVisible.value = false
    
    // 刷新历史记录
    await fetchHistory()
  } catch (error) {
    console.error('回滚失败:', error)
    message.error('回滚失败：' + (error.response?.data?.detail || error.message))
  } finally {
    rollbackLoading.value = false
  }
}

const formatTime = (timeStr) => {
  if (!timeStr) return '-'
  const date = new Date(timeStr)
  return date.toLocaleString('zh-CN', {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit',
    hour: '2-digit',
    minute: '2-digit',
    second: '2-digit'
  })
}

onMounted(() => {
  fetchHistory()
})
</script>

<style scoped>
:deep(.ant-menu-item) {
  font-weight: 500;
  color: #606266;
}

:deep(.ant-menu-item-selected) {
  color: #409eff !important;
  font-weight: 600;
}

:deep(.ant-menu-item-selected::after) {
  border-bottom-color: #409eff !important;
}

:deep(.ant-card-head-title) {
  color: #2c3e50;
  font-weight: 600;
}

:deep(.ant-table) {
  background: white;
}

:deep(.ant-table-thead > tr > th) {
  background: #fafafa;
  color: #2c3e50;
  font-weight: 600;
}

:deep(.ant-btn-primary) {
  background: #409eff;
  border-color: #409eff;
}
</style>


